<template>
  <view class="verify-container">

    <!-- 核销码区域 -->
    <view class="verify-code-section">
      <text class="verify-code-label">核销码</text>
      <text class="verify-code">{{ orderDetail.verifyCode }}</text>
    </view>

    <!-- 服务内容区域 -->
    <view class="content-section">
      <text class="section-title">服务内容</text>
      <view class="service-content">
        <text class="service-item" v-for="(item, index) in orderDetail.serviceContent" :key="index">{{ item }}</text>
        <text class="service-note">(不包含虫尸、水泥、沥青和顽固污渍清理等)</text>
      </view>
    </view>

    <!-- 订单信息区域 -->
    <view class="order-info-section">
      <text class="section-title">订单信息</text>
      <view class="info-content">
        <view class="info-row">
          <text class="info-label">订单价格:</text>
          <text class="info-value">¥{{ orderDetail.orderPrice.toFixed(2) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">实付金额:</text>
          <text class="info-value highlight">¥{{ orderDetail.actualPayment.toFixed(2) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">优惠金额:</text>
          <text class="info-value">¥{{ orderDetail.discountAmount ? orderDetail.discountAmount.toFixed(2) : '0.00' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">订单编号:</text>
          <text class="info-value">{{ orderDetail.orderNumber || orderDetail.orderId || '-' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">支付时间:</text>
          <text class="info-value">{{ orderDetail.paymentTime }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">预约时间:</text>
          <text class="info-value">{{ orderDetail.appointmentTime }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-section">
      <button 
        class="verify-btn" 
        :class="{ 'verify-btn-disabled': orderDetail.status === 2 }"
        :disabled="orderDetail.status === 2"
        @click="confirmVerify"
      >{{ orderDetail.status === 2 ? '已核销' : '确认核销' }}</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import request from '@/utils/request'

// 定义订单详情类型
interface OrderDetail {
  orderId: string;
  verifyCode: string;
  serviceContent: string[];
  orderPrice: number;
  actualPayment: number;
  discountAmount: number;
  orderNumber: string;
  paymentTime: string;
  appointmentTime: string;
  status: number; // 1: 待核销, 2: 已核销
}

// 订单对象类型（根据实际数据结构更新）
interface OrderItem {
  id: number;
  orderId: string;
  name: string;
  createBy: string;
  createTime: string | null;
  orderTime: string;
  payTime: string;
  reservationTime: string;
  price: number;
  status: number;
  type: string;
  verificationCode?: string;
  discount: number;
  preferentialMoney: number | null;
  introduction: string;
  cardId: string | null;
  couponId: string | null;
  deleted: number;
  evaluate: string | null;
  orderStatus: string | null;
  serviceId: string | null;
  serviceTypeId: string | null;
  updateBy: string | null;
  updateTime: string | null;
  verify: string | null;
}



// 订单详情数据
const orderDetail = ref<OrderDetail>({
  orderId: '2020032554565799',
  verifyCode: 'MC-1234-5678-9012',
  serviceContent: [
    'XXX标准洗车服务包含',
    '整车泡沫冲洗擦干',
    '轮胎轮毂冲洗清洁',
    '车内吸尘',
    '内饰铺垫简单除尘'
  ],
  orderPrice: 30.00,
  actualPayment: 25.00,
  discountAmount: 5.00,
  orderNumber: '2020032554565799',
  paymentTime: '2020.03.30 14:40:45',
  status: 1, // 默认待核销状态
  appointmentTime: '2020.03.30 14:40'
});

// 页面加载时获取订单ID或核销码
onMounted(() => {
  // 从路由参数中获取参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = (currentPage as any).options || {};
  
  // 获取订单ID参数
  if (options.orderId) {
    orderDetail.value.orderId = String(options.orderId);
    console.log('加载订单详情:', orderDetail.value.orderId);
  }
  
  // 获取核销码参数（从输入核销码页面传递）
  if (options.code) {
    const verificationCode = String(options.code);
    orderDetail.value.verifyCode = verificationCode;
    console.log('接收到核销码:', verificationCode);
  }
  
  // 获取eventChannel并监听order数据
  const eventChannel = (currentPage as any).getOpenerEventChannel();
  if (eventChannel) {
    // 监听acceptOrderData事件
    eventChannel.on('acceptOrderData', function(data: { order: OrderItem }) {
      console.log('接收到的订单对象:', data.order);
      const order = data.order;
      
      // 计算订单价格和优惠金额
      let orderPrice = order.price; // 默认实付金额
      let discountAmount = 0;
      
      // 根据优惠券类型计算
      if (order.type === '0') {
        // 打折类型：订单价格 = 实付金额 / 折扣
        if (order.discount > 0 && order.discount < 1) {
          orderPrice = order.price / order.discount;
          discountAmount = orderPrice - order.price;
        }
      } else if (order.type === '1') {
        // 满减类型：订单价格 = 实付金额 + 优惠金额
        const preferentialMoney = order.preferentialMoney || 0;
        orderPrice = order.price + preferentialMoney;
        discountAmount = preferentialMoney;
      }
      
      // 将order数据映射到orderDetail
      if (order) {
        orderDetail.value = {
          orderId: String(order.id) || '',
          verifyCode: order.verificationCode || '暂无核销码',
          serviceContent: [
            order.name || '',
            order.introduction || ''
          ],
          orderPrice: orderPrice || 0,
          actualPayment: order.price || 0,
          discountAmount: discountAmount || 0,
          orderNumber: String(order.id) || '',
          paymentTime: order.payTime || '',
          appointmentTime: order.reservationTime || '',
          status: order.status || 1
        };
      }
    });
  }
  
});

// 返回上一页
const handleBack = () => {
  uni.navigateBack();
};

// 确认核销
const confirmVerify = () => {
  uni.showModal({
    title: '核销此订单',
    content: '请您仔细核对订单，此操作不可撤销，请谨慎操作',
    success: (res) => {
      if (res.confirm) {
        // 这里可以调用核销接口
        uni.showLoading({
          title: '核销中...'
        });
        //核销操作
        request({
          url: `/wsy/order/verify/${orderDetail.value.orderId}`,
          method: 'PUT'
        }).then(res => {
          console.log(res)
          if (res.code === 200) {
            uni.showToast({
              title: '核销成功',
              icon: 'success',
              duration: 2000,
              success: () => {
                // 核销成功后返回订单页面
                setTimeout(() => {
                  uni.navigateTo({ url: '/pages/order/order' });
                }, 2000);
              }
            });
          } else {
            uni.showToast({
              title: '核销失败：' + res.msg,
              icon: 'none',
              duration: 2000
            });
          }
        }).catch(err => {
          uni.showToast({
            title: '核销失败：' + err.message,
            icon: 'none',
            duration: 2000
          });
        });
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.verify-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 页面头部 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 120rpx;
  padding: 0 30rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #eeeeee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-left,
.header-right {
  width: 60rpx;
  text-align: center;
}

.back-icon {
  font-size: 48rpx;
  color: #333333;
}

.more-icon {
  font-size: 24rpx;
  color: #333333;
}

.header-title {
  font-size: 36rpx;
  color: #333333;
  font-weight: 600;
}

/* 核销码区域 */
.verify-code-section {
  background-color: #ffffff;
  padding: 40rpx 30rpx;
  margin-bottom: 10rpx;
  text-align: center;
}

.verify-code-label {
  font-size: 28rpx;
  color: #666666;
  display: block;
  margin-bottom: 20rpx;
}

.verify-code {
  font-size: 40rpx;
  color: #333333;
  font-weight: 600;
  letter-spacing: 4rpx;
}

/* 内容区域通用样式 */
.content-section,
.order-info-section {
  background-color: #ffffff;
  padding: 30rpx;
  margin-bottom: 10rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
  margin-bottom: 20rpx;
  display: block;
}

/* 服务内容样式 */
.service-content {
  padding-left: 20rpx;
}

.service-item {
  display: block;
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 16rpx;
  line-height: 1.5;
}

.service-note {
  display: block;
  font-size: 26rpx;
  color: #999999;
  margin-top: 10rpx;
  font-style: italic;
}

/* 订单信息样式 */
.info-content {
  padding-left: 20rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 28rpx;
  color: #666666;
  width: 200rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
  text-align: right;
}

.info-value.highlight {
  color: #ff4d4f;
  font-weight: 600;
}

/* 底部操作按钮 */
.bottom-section {
  padding: 30rpx;
  background-color: #ffffff;
  margin-top: auto;
}

.verify-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  color: #ffffff;
  background-color: #1989fa;
  border-radius: 45rpx;
  border: none;
}

.verify-btn-disabled {
  background-color: #cccccc !important;
  color: #999999;
}

.verify-btn-disabled:active {
  background-color: #cccccc !important;
}
</style>